package com.example.osstest.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.*;
import com.example.osstest.config.AliyunConfig;
import com.example.osstest.vo.FileUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class FileUploadService {
    //允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp",".jpg",
    ".jpeg",".gif",".png"};
    @Autowired
    private OSS ossClient;
    @Autowired
    private AliyunConfig aliyunConfig;

    /**
     * @desc 文件上传
     * @param uploadFile
     * @return
     */

    public FileUploadResult[] upload(MultipartFile[] uploadFile){
        boolean isLegal = true;
        FileUploadResult[] fileUploadResult = new FileUploadResult[uploadFile.length];
        for(int i = 0;i<uploadFile.length;i++){
            fileUploadResult[i]=new FileUploadResult();
            if(uploadFile[i].getOriginalFilename()==""){
                isLegal = false;
            }
            if(!isLegal){
                fileUploadResult[i].setStatus("error");
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = format.format(new Date());
            //文件新路径
            String fileName = uploadFile[i].getOriginalFilename();
            String fileUrl = "file/"+(dateStr + "/" + UUID.randomUUID().toString().replace("-","")+"-"+fileName);

            //上传到阿里云
            try{
                //创建文件夹名
                ossClient.putObject(aliyunConfig.getBucketName(),fileUrl,
                        new ByteArrayInputStream(uploadFile[i].getBytes()));
            }catch (Exception e) {
                e.printStackTrace();
                //上传失败
                fileUploadResult[i].setStatus("error");
//                return fileUploadResult;
            }
            fileUploadResult[i].setStatus("done");
            fileUploadResult[i].setResponse("success");
            //this.aliyunConfig.getUriPrefix()+fileUrl文件路径需要保存到数据库
            fileUploadResult[i].setName(this.aliyunConfig.getUrlPrefix()+fileUrl);
            //System.currentTimeMillis()获得当前时间，String.valueOf()是将当前时间转换成字符串
            fileUploadResult[i].setUid(String.valueOf(System.currentTimeMillis()));
        }
        return fileUploadResult;
    }


    /**
     * @desc 查看文件列表
     * @return
     */
    public List<OSSObjectSummary> list(){
        //设置最大个数
        final int maxKeys = 200;
        //列举文件
        ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(aliyunConfig.getBucketName()).withMaxKeys(maxKeys));
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        return sums;
    }

    /**
     * @desc 删除文件
     * @param objectName
     * @return
     */
    public FileUploadResult delete(String objectName){
        //根据BucketName,objectName删除文件
        ossClient.deleteObject(aliyunConfig.getBucketName(),objectName);
        FileUploadResult fileUploadResult = new FileUploadResult();
        fileUploadResult.setName(objectName);
        fileUploadResult.setStatus("removed");
        fileUploadResult.setResponse("success");
        return fileUploadResult;
    }

    /**
     * @desc 下载文件
     * @param os
     * @param objectName
     * @throws IOException
     */
    public void exportOssFile(OutputStream os,String objectName) throws IOException{
        //ossObject包含文件所在的存储空间名称，文件名称，文件元信息以及一个输入流
        OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(),objectName);
        //读取内容
        BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
        BufferedOutputStream out = new BufferedOutputStream(os);
        //定义一个缓冲区
        byte[] buffer = new byte[1024];
        int lenght = 0;
        while((lenght = in.read(buffer))!=-1){
            //将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此缓冲的输出流。
            out.write(buffer,0,lenght);
        }
        if(out != null){
            out.flush();
            out.close();
        }
        if(in != null){
            in.close();
        }
    }
}
